"use client"

import { useState, useEffect } from "react"
import { RankingSidebar } from "@/components/ranking/ranking-sidebar"
import { RankingContent } from "@/components/ranking/ranking-content"
import { getRankings, getRankingDetail } from "@/lib/api-client"
import { Skeleton } from "@/components/ui/skeleton"
import { Pagination } from "@/components/ui/pagination"
import type { Ranking } from "@/types/ranking"
import type { Song } from "@/types"

export default function RankingPage() {
    const [rankings, setRankings] = useState<Ranking[]>([])
    const [selectedRanking, setSelectedRanking] = useState<Ranking | null>(null)
    const [songs, setSongs] = useState<Song[] | null>(null)
    const [loading, setLoading] = useState(true)
    const [detailLoading, setDetailLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)
    const [page, setPage] = useState(1)
    const [totalPages, setTotalPages] = useState(1)
    const pageSize = 10 // 每页显示10首歌曲

    // 只获取一次排行榜列表
    useEffect(() => {
        async function fetchRankings() {
            try {
                setLoading(true)
                const response = await getRankings()

                if (response.success && response.data && response.data.length > 0) {
                    setRankings(response.data)
                    // 默认选择第一个榜单
                    setSelectedRanking(response.data[0])
                } else {
                    setError("获取排行榜失败")
                }
            } catch (err) {
                setError("获取排行榜失败")
                console.error(err)
            } finally {
                setLoading(false)
            }
        }

        fetchRankings()
    }, []) // 空依赖数组，确保只执行一次

    // 当选中的榜单变化或页码变化时，获取详情
    useEffect(() => {
        async function fetchRankingDetail() {
            if (!selectedRanking) return

            try {
                setDetailLoading(true)
                const response = await getRankingDetail(selectedRanking.id)
                if (response.success && response.data) {
                    // 计算总页数
                    const total = response.data.length
                    setTotalPages(Math.ceil(total / pageSize))

                    // 获取当前页的歌曲
                    const startIndex = (page - 1) * pageSize
                    const endIndex = startIndex + pageSize
                    setSongs(response.data.slice(startIndex, endIndex))
                } else {
                    setError("获取排行榜详情失败")
                }
            } catch (err) {
                setError("获取排行榜详情失败")
                console.error(err)
            } finally {
                setDetailLoading(false)
            }
        }

        fetchRankingDetail()
    }, [selectedRanking, page])

    const handleRankingChange = (ranking: Ranking) => {
        setSelectedRanking(ranking)
        setPage(1) // 切换榜单时重置页码
    }

    const handlePageChange = (newPage: number) => {
        setPage(newPage)
    }

    if (loading) {
        return (
            <div className="min-h-screen">
                <div className="container py-4">
                    <div className="flex gap-6">
                        <div className="w-64">
                            <Skeleton className="h-8 w-48 mb-4" />
                            {Array.from({ length: 5 }).map((_, i) => (
                                <Skeleton key={i} className="h-10 w-full mb-2" />
                            ))}
                        </div>
                        <div className="flex-1">
                            <Skeleton className="h-8 w-48 mb-4" />
                            {Array.from({ length: 10 }).map((_, i) => (
                                <Skeleton key={i} className="h-16 w-full mb-2" />
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        )
    }

    if (error) {
        return (
            <div className="min-h-screen">
                <div className="container py-4">
                    <div className="text-red-500 p-4">{error}</div>
                </div>
            </div>
        )
    }

    return (
        <div className="min-h-screen">
            <div className="container py-4">
                <div className="flex gap-6">
                    <RankingSidebar rankings={rankings} selectedRanking={selectedRanking} onRankingChange={handleRankingChange} />
                    {selectedRanking && (
                        <div className="flex-1 flex flex-col">
                            <RankingContent ranking={selectedRanking} songs={songs} isLoading={detailLoading} />
                            {totalPages > 1 && (
                                <div className="mt-6 flex justify-center">
                                    <Pagination currentPage={page} totalPages={totalPages} onPageChange={handlePageChange} />
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}

